package com.link.base.base.accnt.controller;

import com.link.base.base.accnt.model.AcctAddress;
import com.link.base.base.accnt.service.AcctAddressService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 客户地址Controller
 * </p>
 * <p>
 * Description
 * </p>
 * <p>
 * Company
 * </p>
 *
 * @author yrf
 * @date 2016年7月12日 上午11:38:14
 */

@Controller
@RequestMapping("/link/acctaddress")
public class ProtalAcctAddressController extends BasicController<AcctAddress> {

    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private AcctAddressService acctAddressService;

    @Override
    public BasicService<AcctAddress> getBasicService() throws Exception {
        return acctAddressService;
    }

    /**
     * <p>
     * 接收新建表单地址数据，新建或更新
     * </p>
     *
     * @param records
     * @author yrf
     */
    @RequestMapping(value = "/dealerAddrAdd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addAddress(@RequestBody List<AcctAddress> records) {
        LCLogger.info().withMessageKey("dealerAddrAdd").withMessage("添加客户地址...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        Long acctId = 0L;
        try {
            for (int i = 0; i < records.size(); i++) {
                AcctAddress record = records.get(i);
                acctId = record.getAcctId();
                if (null == acctId) {
                    result.put("success", false);
                    result.put("result", "客户ID不能为空");
                    return result;
                } else {

                    record.setId(keyGenerateService.keyGenerate());
                    acctAddressService.insert(record);
                }

            }
            result.put("acctId", acctId);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>
     * 设置默认地址
     * </p>
     *
     * @param record
     * @author yrf
     */
    @RequestMapping(value = "/setDefaultAddr", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setDefaultAddr(@JsonParam AcctAddress record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        Long addrId = record.getId();
        Long acctId = record.getAcctId();
        if (null == acctId || null == addrId) {
            result.put("success", false);
            result.put("result", "客户与地址ID均不能为空");
            return result;
        }
        try {
            acctAddressService.defaultAddrUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>
     * 联系人设置默认地址
     * </p>
     *
     * @param record
     * @author yrf
     */
    @RequestMapping(value = "/setDefaultContactAddr", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setDefaultContactAddr(@JsonParam AcctAddress record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        Long addrId = record.getId();
        Long contactId = record.getContactId();
        if (null == contactId || null == addrId) {
            result.put("success", false);
            result.put("result", "联系人与地址ID均不能为空");
            return result;
        }
        try {
            acctAddressService.defaultAddrUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>
     * 激活或失效客户地址
     * </p>
     *
     * @param record
     * @author yrf
     */
    @RequestMapping(value = {"/activeAddr", "/inactiveAddr"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setEffectiveAddr(@JsonParam AcctAddress record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        Long addrId = record.getId();
        if (null == addrId) {
            result.put("success", false);
            result.put("result", "地址ID不能为空");
            return result;
        }
        try {
            acctAddressService.effectiveAddrUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通过客户Id 查询记录
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listByAcctId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listByAcctId(@JsonParam QueryParams qps, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<AcctAddress> list = null;
        AcctAddress entity = new AcctAddress();
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            AcctAddress t = (AcctAddress) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            if (qps.getAttr1() != null && !"".equals(qps.getAttr1())) {
                t.setAcctId(Long.parseLong(qps.getAttr1()));
            } else {
                throw new ServiceException("PUBLIC-026!");
            }
            list = acctAddressService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<AcctAddress>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通过联系人Id 查询记录
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listByContactId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listByContactId(@JsonParam QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<AcctAddress> list = null;
        AcctAddress entity = new AcctAddress();
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            AcctAddress t = (AcctAddress) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            if (qps.getAttr1() != null && !"".equals(qps.getAttr1())) {
                t.setContactId(Long.parseLong(qps.getAttr1()));
            } else {
                throw new ServiceException("PUBLIC-016!");
            }
            list = acctAddressService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<AcctAddress>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 设置默认地址
     *
     * @author lizt
     * 2017年3月31日
     */
    @RequestMapping(value = "/setMainAddr", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setMainAddr(@RequestBody AcctAddress entity, HttpSession session, HttpServletRequest request,
                                           HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            acctAddressService.setMainAddr(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 新建或更新一条记录
     * 新增时需判断，若为第一条数据，则设置主要
     *
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/otherUpsert")
    @ResponseBody
    public Map<String, Object> otherUpsert(@JsonParam AcctAddress entity, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        String base = "base";
        try {
            beforUpsert(entity, request);
            checkData(entity, request);
            if (!getBasicService().isInsertFlag(entity) && !checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002！");
            }
            if (getBasicService().isInsertFlag(entity)) {
                Long id = keyGenerateService.keyGenerate();
                Long headId = entity.getAcctId();
                AcctAddress object = new AcctAddress();
                object.setAcctId(headId);
                List<AcctAddress> objectList = acctAddressService.queryByExamplePage(object);
                entity.setId(id);
                getBasicService().insert(entity);
                /*如果当前头对象下无其他记录，则设置为主要数据*/
                if (objectList.size() <= 0) {
                    AcctAddress acctAddress = new AcctAddress();
                    acctAddress.setAcctId(headId);
                    acctAddress.setId(id);
                    acctAddressService.defaultAddrUpdate(acctAddress);
                }
            } else {
                getBasicService().update(entity);
            }

            AcctAddress newEntry = getBasicService().queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 删除一条记录
     * 删除时如为主要，则需要设置下一条最老数据为主要
     *
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/otherDeleteById")
    @ResponseBody
    public Map<String, Object> otherDeleteById(@JsonParam AcctAddress entity, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            beforDelete(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PIUBLIC-031");
            }
            /*判断当前删除数据是不是为主要数据，如为主要则设置下一条最老数据为主要*/
            AcctAddress acctAddress = acctAddressService.queryById(entity);

            getBasicService().deleteById(entity);
            String flag = "Y";
            if (flag.equals(acctAddress.getIsDefault())) {
                AcctAddress object = new AcctAddress();
                object.setAcctId(acctAddress.getAcctId());
                List<AcctAddress> objectList = acctAddressService.queryByExamplePage(object);
                if (objectList.size() > 0) {
                    AcctAddress acctAddressObj = new AcctAddress();
                    acctAddressObj.setAcctId(acctAddress.getAcctId());
                    acctAddressObj.setId(objectList.get(0).getId());
                    acctAddressService.defaultAddrUpdate(acctAddressObj);
                }
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
